﻿<%@ WebHandler Language="C#" Class="GZPrepareImportReport " %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;

/**
 * Description: 工装生产准备导入
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2023.3.22
 **/

public class GZPrepareImportReport : IHttpHandler
{
    public bool IsReusable { get { return false; } }
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    case "validate":
                        r = validate(jObject);//保存前检验批次号是否存在
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveData":
                        r = saveData(jObject);//保存数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getQuerySql(JObject jObject)
    {
        string sql = @"
SELECT t.id,t.containername,t.allsetplandate,t.missingpartsnotes,t.notes,NVL(t.isallset,'否') isallset,
       e.fullname creater,t.createdate,e2.fullname updater,t.lastchangedate
FROM gzpreparemanagement t
LEFT JOIN employee e ON e.employeeid = t.createemployeeid
LEFT JOIN employee e2 ON e2.employeeid = t.lastchangeemployeeid
WHERE 1=1 ";

        // 流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND t.containername = '{0}'", jObject["containername"].ToString());
        }

        // 预齐套时间
        if (jObject["allsetplandate"] != null && jObject["allsetplandate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["allsetplandate"].ToString());
            sql += string.Format(" AND t.allsetplandate >= TO_DATE('{0}','yyyy-mm-dd') ", arr[0].ToString());
            sql += string.Format(" AND t.allsetplandate <= TO_DATE('{0}','yyyy-mm-dd') ", arr[1].ToString());
        }

        // 是否齐套
        if (jObject["isallset"] != null && jObject["isallset"].ToString() != "")
        {
            sql += string.Format(" AND NVL(t.isallset,'否') = '{0}'", jObject["isallset"].ToString());
        }

        // 缺件情况
        if (jObject["missingpartsnotes"] != null && jObject["missingpartsnotes"].ToString() != "")
        {
            sql += string.Format(" AND t.missingpartsnotes LIKE '%{0}%'", jObject["missingpartsnotes"].ToString());
        }

        // 备注
        if (jObject["notes"] != null && jObject["notes"].ToString() != "")
        {
            sql += string.Format(" AND t.notes LIKE '%{0}%'", jObject["notes"].ToString());
        }
        return sql;
    }

    //查询数据
    Result getData(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //校验
    Result validate(JObject jObject)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(jObject["toValidateData"].ToString());
        int islegelQty = 0;
        foreach (DataRow dr in dtPostData.Rows)
        {
            string sql = @"
SELECT COUNT(cci.containerno) qty
FROM containercurrentinfo cci
LEFT JOIN mes_factory_mapping t ON t.factoryid = cci.factoryid
WHERE t.factorycode = '604' AND cci.containername = '{0}'";
            sql = string.Format(sql, dr["containername"].ToString());
            DataTable dt = dal.GetDataTable(sql);
            if (dt.Rows[0]["qty"].ToString() == "0")
            {
                islegelQty += 1;
                dr["islegel"] = 0;
                dr["illegalreason"] = "批次号不存在";
            }
        }
        Result r = new Result();
        r.data = dtPostData;
        r.total = Convert.ToInt32(islegelQty);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //保存数据
    Result saveData(JObject jObject)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(jObject["willBeSavedData"].ToString());
        foreach (DataRow dr in dtPostData.Rows)
        {
            string sql = "SELECT * FROM gzpreparemanagement t WHERE t.containername = '{0}'";
            sql = string.Format(sql, dr["containername"].ToString());
            DataTable dt = dal.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                sql = @"
UPDATE gzpreparemanagement t SET t.containername = '{0}',t.isallset = '{1}',t.allsetplandate = to_date('{2}','yyyy-mm-dd'),
t.missingpartsnotes = '{3}',t.notes = '{4}',
t.lastchangeemployeeid = '{5}',t.lastchangedate = sysdate
WHERE t.containername = '{0}'";
                sql = string.Format(sql,
                    dr["containername"].ToString(),
                    dr["isallset"].ToString(),
                    dr["allsetplandate"].ToString(),
                    dr["missingpartsnotes"].ToString(),
                    dr["notes"].ToString(),
                    jObject["employeeid"].ToString());
                dal.ExecuteSql(sql);
            }
            else
            {
                sql = string.Format("SELECT cci.containerid FROM containercurrentinfo cci WHERE cci.containername = '{0}'", dr["containername"].ToString());
                string containerid = dal.GetDataTable(sql).Rows[0]["containerid"].ToString();
                sql = @"
INSERT INTO gzpreparemanagement(id,containername,isallset,allsetplandate,missingpartsnotes,notes,createemployeeid,createdate,containerid)
VALUES('{0}','{1}','{2}',to_date('{3}','yyyy/mm/dd'),'{4}','{5}','{6}',sysdate,'{7}')";
                sql = string.Format(sql,
                    Guid.NewGuid().ToString(),//唯一id
                    dr["containername"].ToString(),
                    dr["isallset"].ToString(),
                    dr["allsetplandate"].ToString(),
                    dr["missingpartsnotes"].ToString(),
                    dr["notes"].ToString(),
                    jObject["employeeid"].ToString(),
                    containerid);
                dal.ExecuteSql(sql);
            }
        }
        Result r = new Result();
        r.data = dtPostData;
        r.total = Convert.ToInt32(dtPostData.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        dt.Columns.Remove("id");
        dt.Columns["containername"].Caption = "批次号";
        dt.Columns["allsetplandate"].Caption = "预齐套时间";
        dt.Columns["missingpartsnotes"].Caption = "缺件情况";
        dt.Columns["notes"].Caption = "备注";
        dt.Columns["isallset"].Caption = "是否齐套";
        dt.Columns["creater"].Caption = "导入人";
        dt.Columns["createdate"].Caption = "导入时间";
        dt.Columns["updater"].Caption = "修改人";
        dt.Columns["lastchangedate"].Caption = "修改时间";
        ExportHelper.ExportExcel(dt, "工装生产准备已导入数据导出");
    }
}